/* eslint-disable prefer-promise-reject-errors */
import React, { useState, useContext, Fragment } from 'react';
import { Form, Input, Modal, Select, Button, Radio, message } from 'antd';
import { withRouter, useIntl, FormattedMessage } from 'umi';

import { WrapperContext } from '../../containers';
import { SET_DATA } from '../../containers/constants';
import { getNodesList,BulkMigration,startMigration } from '../../../service';

const { TextArea } = Input;
const { Option } = Select;
const { Item: FormItem } = Form;

export default withRouter(
  () => {
    const {
      dispatch,
      state: { allMoveVisible, machineList, startMigrateIp, activeMachineGroupId },
    } = useContext(WrapperContext);
    // Repo配置选择项
    const [repoType, setRepoType] = useState(false);
    // 备份配置选择项
    const [backupType, setBackupType] = useState(false);
    const [form] = Form.useForm();
    const initialValues = {
      kernel: 'ANCK',
      repo_type: 'public',
      version: 'Anolis OS 8',
      backup_type: 'no',
    };
    const intl = useIntl();
    
    const handleAdd = async () => {
      form.validateFields().then(async (values) => {
        if (typeof values === 'undefined') return true;
        const hide = message.loading(`${startMigrateIp === '' ? <FormattedMessage id="pages.migrate.implementation" defaultMessage="Batch implementation" /> : <FormattedMessage id="pages.migrate.configuration" defaultMessage="Migration configuration" />}中...`, 0);
        let params = {...values}
        if(startMigrateIp !== ""){
          params.ip = [startMigrateIp];
          params.step = 0;
        }
        if(params.backup_type === 'no'){
          params.backup_type = '';
        }
        try {
          if(startMigrateIp === ''){
            let {code,msg} = await BulkMigration(params);
            if (code === 200) {
              getList();
              return true;
            }
            message.error(msg);
            return false;
          }else{
            let {code,msg} = await startMigration(params);
            if (code === 200) {
              getList();
              return true;
            }
            message.error(msg);
            return false;
          }
        } catch (error) {
          return false;
        } finally {
          hide();
          setRepoType(false);
          setBackupType(false);
          form.resetFields();
        }
      })
      
    };

    const getList = async () => {
      try {
        const {
          code: queryCode,
          data: nodeList,
        } = await getNodesList({ id: activeMachineGroupId });
        if (queryCode === 200) {
          message.success(`${startMigrateIp === '' ? <FormattedMessage id="pages.migrate.implementation" defaultMessage="Batch implementation" /> : <FormattedMessage id="pages.migrate.configuration" defaultMessage="Migration configuration" />}<FormattedMessage id="pages.journal.task.success" defaultMessage="Success" />`);
          dispatch({
            type: SET_DATA,
            payload: {
              machineList: nodeList && nodeList.length !== 0 ? nodeList : [],
              nodeTotal: nodeList ? nodeList.length : 0,
              allMoveVisible: false,
            },
          });
          return true;
        }
        return false;
      } catch (e) {
        console.log(`<FormattedMessage id="pages.migrate.acquisition" defaultMessage="Failed to update data acquisition, error message:" /> ${e}`);
        return false;
      }
    }
    
    const handleRepo = (e) => {
      if(e.target.value === "public"){
        setRepoType(false);
      }else if(e.target.value === "private"){
        setRepoType(true);
      }
    }

    const handleBackup = (e) => {
      if(e.target.value === "no"){
        setBackupType(false);
      }else if(e.target.value === "nfs"){
        setBackupType(true);
      }
    }

    return (
      <Modal
        wrapClassName="addModal"
        centered
        width={960}
        destroyOnClose
        afterClose={() => form.resetFields()}
        title={startMigrateIp === '' ? <FormattedMessage id="pages.migrate.implementation" defaultMessage="Batch implementation" /> : <FormattedMessage id="pages.migrate.configuration" defaultMessage="Migration configuration" />}
        visible={allMoveVisible}
        onCancel={() => {
          dispatch({
            type: SET_DATA,
            payload: { allMoveVisible: false },
          });
        }}
        footer={[
          <Button
            key="back"
            onClick={() =>{
              form.resetFields();
              dispatch({
                type: SET_DATA,
                payload: { allMoveVisible: false },
              })
              setRepoType(false);
              setBackupType(false);
            }}
          >
            <FormattedMessage id="pages.template.no" defaultMessage="cancel" />
          </Button>,
          <Button key="submit" type="primary" onClick={handleAdd}>
            <FormattedMessage id="pages.template.yes" defaultMessage="confirm" />
          </Button>,
        ]}
      >
        <Form
          layout="horizontal"
          form={form}
          initialValues={initialValues}
          labelCol={{
            span: 4,
          }}
          wrapperCol={{
            span: 18,
          }}
        >
          {
            startMigrateIp === '' ?
            <FormItem 
              name="ip" 
              label={intl.formatMessage({
                id: 'pages.migrate.selectivemachine',
                defaultMessage: 'Selective machine',
              })}
              rules={[{ required: true, message: <FormattedMessage id="pages.migrate.selectmachine_placeholder" defaultMessage="The machine cannot be empty" /> }]}
            >
              <Select placeholder={intl.formatMessage({
                id: 'pages.migrate.selectmachine_please',
                defaultMessage: 'Please select machine',
              })} mode="multiple">
                {
                  machineList && machineList.map((item)=>{
                    return(
                      <Option key={item.ip}>{item.ip}</Option>
                    )
                  })
                }
              </Select>
            </FormItem>
            :
            <FormItem 
              name="ip" 
              label={intl.formatMessage({
                id: 'pages.migrate.selectivemachine',
                defaultMessage: 'Selective machine',
              })}
              required
            >
              <Input value={startMigrateIp} defaultValue={startMigrateIp} disabled/>
            </FormItem>
          }
          <FormItem 
            name="version" 
            label={intl.formatMessage({
              id: 'pages.migrate.migratingversion',
              defaultMessage: 'Migrating version',
            })}
            rules={[{ required: true, message: <FormattedMessage id="pages.migrate.migratingversion_placeholder" defaultMessage="The migration version cannot be empty" /> }]}
          >
            <Select placeholder={intl.formatMessage({
              id: 'pages.migrate.migratingversion_please',
              defaultMessage: 'Select the version you want to migrate',
            })}>
              {/* <Option key="Anolis OS 7">Anolis OS 7</Option> */}
              <Option key="Anolis OS 8">Anolis OS 8</Option>
            </Select>
          </FormItem>
          <FormItem 
            name="kernel" 
            label={intl.formatMessage({
              id: 'pages.migrate.selectkernel',
              defaultMessage: 'Select kernel',
            })}
            rules={[{ required: true, message: <FormattedMessage id="pages.migrate.selectkernel_placeholder" defaultMessage="The kernel cannot be empty" /> }]}
          >
            <Radio.Group >
              <Radio value="ANCK">ANCK</Radio>
              {/* <Radio value="RHCK">RHCK</Radio> */}
            </Radio.Group>
          </FormItem>
          <FormItem 
            name="repo_type" 
            label={intl.formatMessage({
              id: 'pages.migrate.publicaddress',
              defaultMessage: 'Repo configuration',
            })}
            rules={[{ required: true, message: <FormattedMessage id="pages.migrate.repoconfiguration_placeholder" defaultMessage="The Repo configuration cannot be empty" /> }]}
          >
            <Radio.Group onChange={handleRepo}>
              <Radio value="public"><FormattedMessage id="pages.migrate.selectivemachine" defaultMessage="Public address" /></Radio>
              <Radio value="private"><FormattedMessage id="pages.migrate.intranetaddress" defaultMessage="Intranet address" /></Radio>
            </Radio.Group>
          </FormItem>
          {
            repoType && 
            <FormItem name="repo_url" label colon={false}>
              <Input placeholder={intl.formatMessage({
                id: 'pages.migrate.intranetaddress_please',
                defaultMessage: 'Please enter the Intranet address',
              })}/>
            </FormItem>
          }
          <FormItem 
            name="backup_type" 
            label={intl.formatMessage({
              id: 'pages.migrate.backupconfiguration',
              defaultMessage: 'Backup configuration',
            })}
            rules={[{ required: true, message: <FormattedMessage id="pages.migrate.backupconfiguration_placeholder" defaultMessage="The backup configuration cannot be empty" /> }]}
          >
            <Radio.Group onChange={handleBackup}>
              <Radio value="no"><FormattedMessage id="pages.migrate.nobackup" defaultMessage="No backup" /></Radio>
              <Radio value="nfs"><FormattedMessage id="pages.migrate.nfsbackup" defaultMessage="NFS backup" /></Radio>
            </Radio.Group>
          </FormItem>
          {
            backupType && 
            <Fragment>
              <FormItem name="backup_ip" label colon={false}>
                <Input placeholder={intl.formatMessage({
                  id: 'pages.migrate.nfsbackupipadress_please',
                  defaultMessage: 'Enter the IP address of the NFS service',
                })}/>
              </FormItem>
              <FormItem name="backup_path" label colon={false}>
                <Input placeholder={intl.formatMessage({
                  id: 'pages.migrate.backunfs_please',
                  defaultMessage: 'Please enter the directory where the backup is stored in the NFS',
                })}/>
              </FormItem>
              <FormItem name="backup_exclude" label colon={false}>
                <Input placeholder={intl.formatMessage({
                  id: 'pages.migrate.notneedbackup_please',
                  defaultMessage: 'Enter a directory that does not need to be backed up',
                })}/>
              </FormItem>
            </Fragment>
          }
        </Form>
      </Modal>
    );
  },
);
